package com.tao.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tao.pojo.User;
import com.tao.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    UserService userService;

   @RequestMapping("/register")
   public String register(User user){
       JSONObject o = new JSONObject();


       User user0 = userService.selectByname(user.getUsername());
       if ( user0==null){
            System.out.println("不存在");
            userService.insertUser(user);
           o.put("msg","insert");

       }else {
            System.out.println("存在"+user0.toString());
           o.put("msg","success");

       }

//       JSON对象
       System.out.println(user);
       //转为字符串
       return JSON.toJSONString(o);
   }



    @RequestMapping("/login")
    public String login(String  username,String password){
       System.out.println("登陆2");
//      获取当前用户
       Subject subject = SecurityUtils.getSubject();
       JSONObject o = new JSONObject();
//        封装用户数据  令牌token加密
       UsernamePasswordToken token = new UsernamePasswordToken(username,password);
//       System.out.println("username:"+username+",passwold:"+password);
       //执行登陆方法
       try {
           subject.login(token);
           o.put("msg","success");
           User user = userService.selectByname(username);
           o.put("headimg",user.getHead());
           o.put("userid",user.getId());

       } catch (UnknownAccountException e) {//用户名不存在
           o.put("msg","null");
           System.out.println("用户名不存在");
       }catch (IncorrectCredentialsException e){
           System.out.println("密码错误");
           o.put("msg","error");
       }
       o.put("test","数据测试");
       System.out.println(o);
       return JSON.toJSONString(o);
   }



//    selectAll
    @ApiOperation("查询用户的方法")
    @RequestMapping("/selectAll")
    public String selectALL(){
        List<User> users = userService.selectAll();

        String s = JSON.toJSONString(users);

        return s;
    }

    //del
    @RequestMapping("/delUser/{id}")
    public String delUser(@PathVariable int id){

//        System.out.println("del:"+id);
        userService.deleteByPrimaryKey(id);
       return JSON.toJSONString("success");
    }
}
